package com.example.xmpic.ui.utils;

import android.content.Context;
import android.os.Build;
import android.util.Log;

import com.example.common.utils.SpUtil;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.ui.data.DaoMaster;
import com.example.xmpic.ui.data.DaoSession;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;

/**
 * @author skygge
 * @date 2020/5/6.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：拷贝/加载本地SO库
 */
public class FunSdkInitUtil {
    private static final String TAG = FunSdkInitUtil.class.getSimpleName();
    private static final String TARGET_LIBS_NAME = "xm_libs";

    public static volatile FunSdkInitUtil instance;

    private Context mContext;
    private WeakReference<Context> weakReference;

    private DaoSession mDaoSession;

    private FunSdkInitUtil(){
    }

    private FunSdkInitUtil(Context context) {
        this.mContext = context;
        weakReference = new WeakReference<>(context);
    }

    public static FunSdkInitUtil getInstance() {
        if (instance == null) {
            synchronized (FunSdkInitUtil.class) {
                if (instance == null) {
                    instance = new FunSdkInitUtil();
                }
            }
        }
        return instance;
    }

    public static FunSdkInitUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (FunSdkInitUtil.class) {
                if (instance == null) {
                    instance = new FunSdkInitUtil(context);
                }
            }
        }
        return instance;
    }

    /**
     * 初始化雄迈摄像头SDK
     */
    public void initFunSDK(){
        if (getSoSourcePath()){
            FunSupport.getInstance().init(weakReference.get());
        }else {
            copySo();
        }
    }

    /**
     * 私有目录so文件是否存在
     * @return true
     */
    private boolean getSoSourcePath() {
        //目标目录
        File targetDir = weakReference.get().getDir(TARGET_LIBS_NAME, Context.MODE_PRIVATE);
        //创建目录
        if (targetDir.exists()) {
            File[] currentFiles = targetDir.listFiles();
            if (currentFiles != null && currentFiles.length == 3) {
                for (File currentFile : currentFiles) {
                    if (currentFile.getName().contains("libFunSDK")) {
                        Log.i(TAG, "getSoSourcePath: 文件存在");
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * true覆盖原文件即删除原有文件后拷贝新的文件进来
     */
    private void copySo() {
        String[] fileNames; //要复制的文件
        String localFileName; //要复制的文件目录名称
        try {
            if (is64bitCPU()){
                fileNames = weakReference.get().getApplicationContext().getAssets().list("arm64-v8a");
                localFileName = "arm64-v8a";
            }else {
                fileNames = weakReference.get().getApplicationContext().getAssets().list("armeabi");
                localFileName = "armeabi";
            }
            //目标目录
            File targetDir = weakReference.get().getDir(TARGET_LIBS_NAME, Context.MODE_PRIVATE);
            //创建目录
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            } else {
                //删除全部老文件
                for (File file : targetDir.listFiles()) {
                    file.delete();
                }
            }
            if (fileNames != null) {
                for (String currentFile:fileNames) {
                    if (currentFile.contains(".so")) {
                        copyFilesAssets(localFileName + File.separator +  currentFile,
                                targetDir.toString()+ File.separator + currentFile);
                        Log.i(TAG, "copySo: success");
                    }
                }
            }
            if (getSoSourcePath()){
                FunSupport.getInstance().init(weakReference.get());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i("AAA", "copySo: 拷贝完成");
    }

    /**
     * 文件拷贝(要复制的目录下的所有非文件夹的文件拷贝)
     * 将旧目录中的文件全部复制到新目录
     */
    private void copyFilesAssets(String oldPath, String newPath) {
        try {
            InputStream is = weakReference.get().getAssets().open(oldPath);
            FileOutputStream fos = new FileOutputStream(new File(newPath));
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 判断当前手机的CPU架构
     * @return true/false
     */
    private static boolean is64bitCPU() {
        String CPU_ABI = null;
        if (Build.VERSION.SDK_INT >= 21) {
            String[] CPU_ABIS = Build.SUPPORTED_ABIS;
            if (CPU_ABIS.length > 0) {
                CPU_ABI = CPU_ABIS[0];
            }
        } else {
            CPU_ABI = Build.CPU_ABI;
        }
        return CPU_ABI != null && CPU_ABI.contains("arm64");
    }

    public void setDatabase() {
        String userLoginId = SpUtil.getString(mContext, "user_login_id", "CameraBean.db");
        String DB_NAME = "camera_" + userLoginId;
        DaoMaster.DevOpenHelper mHelper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null);
        DaoMaster mDaoMaster = new DaoMaster(mHelper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }
}
